package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.ArrayList;
//import java.util.Collection;

import excepcion.ExcepcionDAO;
import modelo.Banco;
import util.ConexionBD;

public class BancoDAO extends BaseDAO {

	public Banco insertar(Banco vo) throws ExcepcionDAO {
		String query = "insert into banco(descripcion) values (?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(2, vo.getDescripcion());
			int i = stmt.executeUpdate();
			//int representa # de filas afectadas. si es insert es (0,1) si es update o delete (0,1,n)
			if (i != 1) {
				throw new SQLException("No se pudo insertar");
			}
			// Obtener el ultimo id
			int id = 0;
			query = "select last_insert_id()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			vo.setIdBanco(id);

		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new ExcepcionDAO(e.getMessage());
		} finally {
		
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}

	public Banco obtener(int idBanco) throws ExcepcionDAO {
		Banco vo = new Banco();
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			String query = "select idBanco,descripcion from banco where idBanco=?";
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setInt(1, idBanco);
			rs = stmt.executeQuery();
			if (rs.next()) {
				vo.setIdBanco(rs.getInt(1));
				vo.setDescripcion(rs.getString(2));
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new ExcepcionDAO(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}
	
}
